<script setup lang="ts">
import { getCategoryList, getCategoryBrandList, getCategoryBrandProList } from '../../api/kind';
import { ref, Ref } from 'vue';
import { iPro } from '../../utils/homeType';
import { useRouter } from 'vue-router';

const router = useRouter()

// 标记分类是哪个
const active: Ref<number> = ref(0)
// 标记选中品牌
const active2: Ref<number> = ref(0)

// 用来接收分类列表数据用的
const categoryList: Ref<string[]> = ref([])

// 用来放品牌的数组
const brandList: Ref<{ brand: string }[]> = ref([])

// 用来接收商品数据用的数组
const proList: Ref<iPro[]> = ref([])

// 用来获取分类列表的函数
getCategoryList().then(res => {
  categoryList.value = res.data.data

  // 请求某分类下的所有品牌
  getCategoryBrandList({
    category: categoryList.value[0]
  }).then(res => {
    // console.log(res.data.data);
    brandList.value = res.data.data

    // 品牌请求成功之后获取商品列表
    getCategoryBrandProList({
      category: categoryList.value[0],
      brand: brandList.value[0].brand
    }).then(res => {
      // console.log(res.data.data);
      proList.value = res.data.data
    })
  })
})

// 监听分类列表的切换
function onChange(index: number): void {
  active.value = index;
  active2.value = 0
  // 请求某分类下的所有品牌
  getCategoryBrandList({
    category: categoryList.value[index]
  }).then(res => {
    brandList.value = res.data.data

    // 品牌请求成功之后获取商品列表
    getCategoryBrandProList({
      category: categoryList.value[index],
      brand: brandList.value[0].brand
    }).then(res => {
      // console.log(res.data.data);
      proList.value = res.data.data
    })

  })
}

// 品牌的点击事件
function clickTab(data: { title: string }): void {
  // console.log(data);
  // 品牌请求成功之后获取商品列表
  getCategoryBrandProList({
    category: categoryList.value[active.value],
    brand: data.title
  }).then(res => {
    // console.log(res.data.data);
    proList.value = res.data.data
  })
}

// 点击商品进入详情页面
function goDetail(proid: string): void {
  router.push({
    path: '/detail',
    query: {
      proid
    }
  })
}
</script>
<template>
  <div class="box">
    <header class="header"> 分类 </header>
    <div class="content">

      <div class="left">
        <van-sidebar v-model="active" @change="onChange">
          <van-sidebar-item v-for="item in categoryList" :key="item" :title="item" />
        </van-sidebar>
      </div>

      <div class="right">
        <van-tabs v-model:active="active2" line-height="0" @click-tab="clickTab" title-active-color="#f66">
          <van-tab v-for="item in brandList" :key="item.brand" :title="item.brand"></van-tab>
        </van-tabs>

        <!-- 某分类某品牌下的产品 -->
        <van-grid :column-num="3">
          <van-grid-item v-for="item in proList" :icon="item.img1" :text="item.brand" @click="goDetail(item.proid)" />
        </van-grid>
      </div>


    </div>
  </div>
</template>
<style scoped lang="scss">
.content {
  display: flex;

  .left {
    width: 25%;
    height: 100%;
    overflow: auto;
  }

  .right {
    width: 75%;
  }
}
</style>
